package com.fs.controller.user;


import com.fs.constant.JwtClaimsConstant;
import com.fs.dto.ResetDTO;
import com.fs.dto.UserDTO;
import com.fs.dto.UserLoginDTO;
import com.fs.dto.UserRegisterDTO;
import com.fs.entity.User;
import com.fs.properties.JwtProperties;
import com.fs.result.Result;
import com.fs.service.UserService;
import com.fs.utils.JwtUtil;
import com.fs.vo.UserLoginVO;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/users")
@Slf4j
@Api(tags = "用户相关接口")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    /*用户注册*/
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public Result register(@RequestBody UserRegisterDTO registerDTO) {
        log.info("用户注册：{}", registerDTO);
        String register = userService.register(registerDTO);
        return Result.success(register);
    }

    /*用户登录*/
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录：{}", userLoginDTO);

        User user = userService.login(userLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }


    /*退出登录*/
    @PostMapping("/logout")
    @ApiOperation("退出登录")
    public Result<String> logout(){
        return Result.success();
    }


    /*根据id查询用户资料*/
    @GetMapping("/view")
    @ApiOperation("根据ID查询用户资料")
    public Result<User> getById(HttpServletRequest request) {
        //从token中获取userid
        Long userId = TokenUserId(request);
        log.info("用户id：{}",userId);
        User user = userService.getById(userId);
        return Result.success(user);
    }

    /*编辑用户信息资料*/
    @PutMapping
    @ApiOperation("编辑用户信息资料")
    public Result updateById(@RequestBody UserDTO userDTO) {
        log.info("编辑用户信息资料：{}",userDTO);
        String message = userService.update(userDTO);
        return Result.success(message);
    }



    //获取token中的userid
    private Long TokenUserId(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            token = request.getHeader("token"); // 兼容 Swagger
        }

        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        // 解密 token
        String secretKey = jwtProperties.getAdminSecretKey();
        Claims claims = JwtUtil.parseJWT(secretKey, token);
        // ⚠️ 注意这里改成 userId（与生成端一致）
        Object userIdObj = claims.get(JwtClaimsConstant.USER_ID);
        Long userId = Long.valueOf(userIdObj.toString());
        return userId;
    }

}
